<template>
    <div class="fillcontain">
        <div class="table_container">
            <el-button type="primary" @click="add">添加场馆</el-button>
          <el-table :data="tableData"  style="width: 700px" align='center'  >
            <el-table-column  property="name" label="场馆名称" width="300" align='left'></el-table-column>
              <el-table-column  property="operation"  label="管理员"   width="160"  align='left'>
                  <template slot-scope='scope'>
                      <router-link :to="{ path: 'manage', query: { stadium: scope.row.id}}">
                        <el-button type="warning" icon='edit' size="small"  @click='onDetail(scope.row.id)'>点击查看详情</el-button>
                      </router-link>
                  </template>
              </el-table-column>
            <el-table-column
                prop="operation"
                align='left'
                label="操作"
                width="180">
                <template slot-scope='scope'>
                    <el-button type="warning" icon='edit'  size="small" @click='onEdit(scope.row,scope.row.id)' >编辑</el-button>
                    <el-button  type="danger"  icon='delete'  size="small"  @click='onDelete(scope.row.id)' >删除</el-button>
                </template>
            </el-table-column>
          </el-table>
            <el-row>
                <el-col :span="24">
                    <div class="pagination">
                        <el-pagination
                            v-if='paginations.total > 0'
                            :page-sizes="paginations.page_sizes"
                            :page-size="paginations.page_size"
                            :layout="paginations.layout"
                            :total="paginations.total"
                            :current-page='paginations.page_index'
                            @current-change='handleCurrentChange'
                            @size-change='handleSizeChange'>
                        </el-pagination>
                    </div>
                </el-col>
            </el-row>
    </div>
        <el-dialog
                title="修改"
                :visible.sync="dialogVisible"
                :modal-append-to-body="false"
                  >
            <div class="form">
            <el-form
                    :inline="true"
                    :model='articleData'
                    ref="articleData"
                    class="demo-form-inline">
                <div class="form-content">
                    <el-row>
                        <el-form-item  label="场馆名称:" prop="name">
                            <el-input type="text" class="area" clearable :rows="1" autosize placeholder="请输入场馆名称" v-model="articleData.name">
                            </el-input>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item  label="场馆地址:" prop="address">
                            <el-input type="text" style="width: 330px;" class="area" clearable :rows="1" autosize placeholder="请输入场馆地址" v-model="articleData.address">
                            </el-input>
                        </el-form-item>
                    </el-row>

                </div>
            </el-form>
            <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editStadium('articleData')">确 定</el-button>
            </span>
            </div>
        </el-dialog>
        <el-dialog   title="添加场馆"
                :visible.sync="dialogAddVisible"
                :modal-append-to-body="false" >
        <el-form
                :inline="true"
                :model='articleData'
                ref="articleData"
                :rules="rules"
                class="demo-form-inline">
            <div class="form-content">
                <el-row>
                    <el-form-item  label="场馆名称:" prop="name">
                        <el-input type="text" class="area" clearable :rows="1" autosize placeholder="请输入场馆名称" v-model="articleData.name">
                        </el-input>
                    </el-form-item>

                </el-row>
                <el-row>
                    <el-form-item  label="场馆地址:" prop="address">
                        <el-input type="text" style="width: 330px;" class="area" clearable :rows="1" autosize placeholder="请输入场馆地址" v-model="articleData.address">
                        </el-input>
                    </el-form-item>
                </el-row>
                <div class="form-tinymce-container">
                    <div class="publish-container">
                        <el-button type="primary" class="publish"  @click='publishArticle("articleData")'>确定</el-button>
                        <el-button type="primary" class="publish"  @click='cancel()'>重置</el-button>
                        <el-button type="danger" class="publish"  @click='close()'>关闭</el-button>
                    </div>
                </div>

            </div>
        </el-form>
        </el-dialog>
    </div>

</template>

<script>
    import dtime from 'time-formater'
    import * as mUtils from '@/utils/mUtils'
    import {axios} from 'utils/'

    export default {
        data(){
            return {
                tableData: [],
                tableHeight:'',
                idFlag:false,
                tokenAccess:'',
                id:'',
                dialogVisible:false,
                dialogAddVisible:false,
                sortnum:0,
                articleData:{
                    name:'',
                    address:''
                },
                rules: {
                    name: [{ required: true,message: '场馆名称为必填项~',trigger : 'blur' }],
                    address: [{ required: true,message: '场馆地址为必填项~' ,trigger : 'blur'}],
                },
                formData:{
                  id:'',
                  name:'',
                  address:''
                },
                //需要给分页组件传的信息
                paginations: {
                    page_index: 1,  // 当前位于哪页
                    total: 0,        // 总数
                    page_size: 20,   // 1页显示多少条
                    page_sizes: [5, 10, 15, 20],  //每页显示多少条
                    layout: "total, sizes, prev, pager, next, jumper"   // 翻页属性
                }


            }
        },
      	mounted() {
            //加载数据之前，先加载theme颜色
            this.getList({
                fun: () => {}
            });
	   },
        created() {
            this.tokenAccess =  mUtils.getStore('tokenAccess');
        },
        methods: {
            /**
            * 格式化状态
            */
            formatterType(item) {
                const type = parseInt(item.incomePayType);
                return this.format_type_list[type];
            },
            filterType(value, item) {
                const type = parseInt(item.incomePayType);
                return this.format_type_list[value] == this.format_type_list[type];
            },
            onDetail(id){
                console.log(id);
            },
            add(){
              this.dialogAddVisible = true;
              this.cancel();
            },
            publishArticle(formTag){
                this.$refs[formTag].validate((valid) => {
                    if (valid) {//表单数据验证完成之后，提交数据;

                        let formData = this.articleData;
                        let userString = '';
                        for (let index in formData){
                            userString += index+"="+formData[index]+'&'
                        }

                        this.saveStadium(userString,'POST');
                        this.dialogAddVisible = false;
                        this.getList();
                    }
                })
            },
            editStadium(formTag){
                this.formData.name = this.articleData.name;
                this.formData.address = this.articleData.address;
                this.formData.id = this.articleData.id ;
                if(this.formData.address != '' && this.formData.name != '' && this.formData.id != ''){
                    let userString = '';
                    for (let index in this.formData){
                        userString += index+"="+this.formData[index]+'&'
                    }
                    this.saveStadium(userString,'PUT');
                }else{
                    this.$message.error('保存失败,请填写正确的场馆名称和地址')
                }

            },
            saveStadium(data, type){
                axios({
                    type: type,
                    path: 'http://59.110.70.252:8031/stadiums',
                    data: data,
                    fn: res=>{
                        //console.log(res);
                        if(res.success == true){
                            this.$message({title:'保存成功',type:'success'});
                            this.articleData.name = '';
                            this.articleData.address = '';
                            this.articleData.id = '';
                            this.dialogVisible = false;
                            this.getList();
                        }else{
                            this.$message.error('保存失败请重试')
                        }
                    },
                    errFn:(err)=>{
                        this.$message.error('保存失败请重试,'+err)
                    },
                    headers:{
                        'x-access-token':this.tokenAccess,
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
            },
            cancel(){
                this.articleData.name = '';
                this.articleData.address = '';
            },
            close(){
                this.cancel();
                this.dialogAddVisible = false;
            },
            randomFrom(lowerValue,upperValue)
            {
                return Math.floor(Math.random() * (upperValue - lowerValue + 1) + lowerValue);
            },
            /**
            * 改变页码和当前页时需要拼装的路径方法
            * @param {string} field 参数字段名
            * @param {string} value 参数字段值
            */
            setPath(field, value) {
                var path  = this.$route.path,
                    query = Object.assign({}, this.$route.query);
                if (typeof field === 'object') {
                    query = field;
                } else {
                    query[field] = value;
                }
                this.$router.push({
                    path,
                    query
                });
            },

            getList({
                page,
                page_size,
                where,
                fun
            } = {}){
                var query = this.$route.query;
                this.paginations.page_index = page || parseInt(query.page) || 1;
                this.paginations.page_size  = page_size || parseInt(query.page_size) || this.paginations.page_size;
                var data = {
                    pageIndex: this.paginations.page_index,
                    pageSize: this.paginations.page_size
                };
                if (where) {
				   data = Object.assign(data, where || {});
                }
                // 封装  get,path,params,fn,errfn
                axios({
                    type:'get',
                    path:'http://59.110.70.252:8031/stadiums?pageNo='+this.paginations.page_index+'&pageSize='+this.paginations.page_size,
                    fn:data=>{
                        //成功之后的回调函数
                        this.paginations.total = data.total;
                        this.tableData = [];
                    	data.data.forEach((item,index) => {
                    	  	const tableItem = {
                                name:item.name,
                                address:item.address,
                                detail:'点击查看',
                                id:item.id

                    		}
                    		this.tableData.push(tableItem);
                        })
                        fun && fun();
                    },
                    headers:{
                        'x-access-token':this.tokenAccess,
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }

                })
           },
            // 操作方法
            onEdit(row,id){
                this.articleData.id = id;
                this.articleData.name = row.name;
                this.articleData.address = row.address;
                this.dialogVisible = true;
            },
            onDelete(id){
                //根据id来删除数据
                console.log(id);
                if(id != ''){
                    axios({
                        type:'DELETE',
                        path:'http://59.110.70.252:8031/stadiums?id=' +id,
                        data: {},
                        fn:data=>{
                            this.$message({
                                showClose: true,
                                    message: '删除成功',
                                    type: 'success'
                            }),
                            this.getList({fun: () => {} });     // 删除成功后，重新加载数据;
                        },
                        errFn:()=>{
                            this.$message.error('删除失败请重试')
                        },
                        headers:{
                            'x-access-token':this.tokenAccess,
                            'Content-Type': 'application/x-www-form-urlencoded'
                        }
                    })
                }else{
                    this.$message.error('删除失败')
                }
            },

            // 每页多少条切换
            handleSizeChange(page_size) {
               this.getList({
                    page_size,
                    fun: () => {
                        this.setPath('page_size', page_size);
                    }
			   });
            },
            // 上下分页
            handleCurrentChange(page) {
               this.sortnum = this.paginations.page_size*(page-1);
               this.getList({
                    page,
                    fun: () => {
                        this.setPath('page', page);
                    }
                });
            },

        },
    }
</script>

<style lang="less" scoped>
     .btnRight{
        float: right;
        margin-right: 0px !important;
    }
    .search-form{
        width:100%;
        min-width:750px;
        .el-form-item{
            margin-bottom: 10px !important;
             .el-date-editor{
                width:200px;
                .el-input__inner{
                    height:36px !important;
                }
            }
        }
    }

    .el-dialog--small{
       width: 600px !important;
    }
    .pagination{
        text-align: left;
        margin-top: 10px;
    }

</style>


